package cn.serenedream.housedecoration.controller;

import java.math.BigDecimal;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.serenedream.housedecoration.dto.OrderData;
import cn.hutool.core.util.IdUtil;
import cn.serenedream.housedecoration.dto.SaleDTO;
import cn.serenedream.housedecoration.entity.*;
import cn.serenedream.housedecoration.result.ProductsResult;
import cn.serenedream.housedecoration.result.SaleProductsResult;
import cn.serenedream.housedecoration.result.SaleResult;
import cn.serenedream.housedecoration.result.UserResult;
import cn.serenedream.housedecoration.serivce.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("sale")
public class SaleController {
    @Autowired
    SaleService saleService;

    @Autowired
    ProductsService productsService;

    @Autowired
    UserService userService;

    @Autowired
    SaleProductsService saleProductsService;

    @Autowired
    SaleSaleProductsService saleSaleProductsService;

    @GetMapping("")
    public String listSales(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "current", defaultValue = "0") int current,
            @RequestParam(value = "page", defaultValue = "10") int size,
            HttpServletRequest httpServletRequest,
            Model model) {

        Pageable pageable = PageRequest.of(current, size);
        Page<Sale> salesPage;

        if (name != null && !name.isEmpty()) {
            // 根据客户名称搜索
            salesPage = saleService.findByUserNameContaining(name, pageable);
            model.addAttribute("searchName", name);
        } else {
            // 获取所有报表
            salesPage = saleService.list(current, size);
        }

        model.addAttribute("sales", salesPage);
        model.addAttribute("requestURI", httpServletRequest.getRequestURI());
        return "classify/sale"; // 返回你的Thymeleaf模板名称
    }

    @GetMapping("delete/{id}")
    public String delete(@PathVariable String id) {
        saleService.delete(id);
        return "redirect:/sale";
    }

    @GetMapping("addOrEdit")
    public String addOrEditList(Model model) {
        extracted(model);

        List<User> userList = userService.findAll();
        List<UserResult> userResults = BeanUtil.copyToList(userList, UserResult.class);

        model.addAttribute("userList", userResults);

        return "classify/addOrEdit/addOrEdit";
    }

    private void extracted(Model model) {
        Page<Products> products = productsService.list(0, Integer.MAX_VALUE);
        List<ProductsResult> productsResults = new ArrayList<>();

        for (Products product : products) {
            ProductsResult productsResult = getProductsResult(product);

            productsResults.add(productsResult);
        }


        model.addAttribute("products", productsResults);
    }

    private static ProductsResult getProductsResult(Products product) {
        ProductsResult productsResult = new ProductsResult();

        productsResult.setId(product.getId().toString());
        productsResult.setName(product.getName());
        productsResult.setPrice(product.getPrice());
        productsResult.setAddress(product.getAddress());
        productsResult.setModel(new cn.serenedream.housedecoration.result.ModelResult(
                product.getModel().getId().toString(),
                product.getModel().getSize(),
                product.getModel().getThickness()));
        return productsResult;
    }

    @PostMapping("save-saleProducts")
    public String saveSaleProducts(@RequestBody OrderData orderData) {
        System.out.println(orderData);

        List<SaleProducts> saleProductsList = new ArrayList<>();
        for (Map<String, String> stringStringMap : orderData.getSaleProducts()) {
            // SaleProducts
            SaleProducts saleProducts = new SaleProducts();
            saleProducts.setId(IdUtil.getSnowflakeNextId());

            for (String s : stringStringMap.keySet()) {
                BigDecimal quantity = new BigDecimal(stringStringMap.get("quantity"));
                BigDecimal unitPrice = new BigDecimal(stringStringMap.get("unitPrice"));

                saleProducts.setProducts(productsService.findById(stringStringMap.get("productId")));
                saleProducts.setNumber(quantity.intValue());

                BigDecimal price = quantity.multiply(unitPrice);
                saleProducts.setPrice(price.doubleValue());
            }
            saleProductsList.add(saleProducts);

            // SaleProducts
            saleProductsService.save(saleProducts);
        }

        Sale sale = new Sale();
        sale.setPrice(new BigDecimal(orderData.getTotalAmount()).doubleValue());
        sale.setCreateDate(DateTime.now());
        sale.setUser(userService.findById(orderData.getUserId()));

        // 保存 Sale SaleProducts & SaleSaleProducts
        // Sale
        if (orderData.getSaleId() != null){
            sale.setId(Long.valueOf(orderData.getSaleId()));
            saleService.save(sale);
        } else {
            sale.setId(IdUtil.getSnowflakeNextId());
            saleService.insert(sale);
        }

        // SaleSaleProducts
        for (SaleProducts saleProducts : saleProductsList) {
            SaleSaleProducts saleSaleProducts = new SaleSaleProducts();

            saleSaleProducts.setId(IdUtil.getSnowflakeNextId());
            saleSaleProducts.setSale(sale);
            saleSaleProducts.setSaleProducts(saleProducts);

            saleSaleProductsService.save(saleSaleProducts);
        }

        return "redirect:/sale";
    }

    @GetMapping("edit/{id}")
    public String toEditSaleProducts(@PathVariable String id, Model model){
        User user = saleService.findUserById(id);
        UserResult userResult = BeanUtil.copyProperties(user, UserResult.class);

        List<SaleProducts> saleProductsList = saleProductsService.findBySaleId(id);
        List<SaleProductsResult> saleProductsResults = BeanUtil.copyToList(saleProductsList, SaleProductsResult.class);

        extracted(model);
        model.addAttribute("saleProductsList", saleProductsResults);
        model.addAttribute("user", userResult);
        model.addAttribute("saleId", id);
        return "/classify/addOrEdit/addOrEdit";
    }

    @GetMapping("detail/{id}")
    public String detail(@PathVariable String id, Model model){
        User user = saleService.findUserById(id);
        UserResult userResult = BeanUtil.copyProperties(user, UserResult.class);
        Sale sale = saleService.findById(id);
        SaleResult saleResult = BeanUtil.copyProperties(sale, SaleResult.class);

        List<SaleProducts> saleProductsList = saleProductsService.findBySaleId(id);
        List<SaleProductsResult> saleProductsResults = BeanUtil.copyToList(saleProductsList, SaleProductsResult.class);

        extracted(model);
        model.addAttribute("sale", saleResult);
        model.addAttribute("saleProductsList", saleProductsResults);
        model.addAttribute("user", userResult);
        return "/classify/excel";
    }
}
